import cv2

# 输入视频路径和输出视频路径
video_path = './data/videos/video1.mp4'  # 输入视频路径
output_video_path = './data/videos/output_video.mp4'  # 输出视频路径


# 打开视频文件
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
    print("Error opening video file")
    exit()

# 获取视频的帧率和尺寸
fps = cap.get(cv2.CAP_PROP_FPS)
frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

# 初始化视频写入器
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
out = cv2.VideoWriter(output_video_path, fourcc, fps, (frame_width, frame_height))

# 假设GOP大小为12（常见值）
gop_size = 12
frame_index = 0

# 遍历视频帧
while cap.isOpened():
    ret, frame = cap.read()
    if not ret:
        break

    # 判断是否为关键帧
    if frame_index % gop_size == 0:
        out.write(frame)
        print(f"Key frame written at index {frame_index}")

    frame_index += 1

# 释放资源
cap.release()
out.release()
cv2.destroyAllWindows()